<?php
/**
 * User: seven
 * Date: 2018/3/4
 * Time: 下午11:22
 */

class Lang2{

    const ENCODING = "utf-8";

    public static function redirect($url){
        self::setHeader("Location", $url);
    }

    public static function flashSet($key, $value){
        self::setSession("_flash_$key", $value);
    }

    public static function flashGet($key, $defaultValue){
        $res = self::getSession("_flash_$key", $defaultValue);
        self::removeSession("_flash_$key");
        return $res;
    }

    ///========================================================///
    public static  function isEmpty($arr){
        if($arr == null) return true;

        if(is_array($arr)){
            if(empty($arr)) return true;
            else return false;
        }

        if(is_string($arr)){
            return strlen($arr) == 0;
        }

        return false;
    }


    public static function isNotEmpty($arr){
        return !self::isEmpty($arr);
    }


    public static function count($a){
        if(is_array($a)){
            return count($a);
        }else if(is_string($a)){
            return mb_strlen($a, self::ENCODING);
        }else{
            return 1;
        }
    }

    public static function snull($str, $valueIfEmptyOrNull){
        if($str == null || trim($str) === ''){
            return $valueIfEmptyOrNull;
        }else{
            return $str;
        }
    }

    public static function indexOf($src, $needle, $start=0){
        $index = mb_strpos($src, $needle, $start, self::ENCODING);
        if($index === false){
            return -1;
        }else{
            return $index;
        }
    }

    public static function lastIndexOf($src, $needle, $start=0){
        $index = mb_strrpos($src, $needle, $start, self::ENCODING);
        if($index === false){
            return -1;
        }else{
            return $index;
        }
    }

    /**
     * @param $src
     * @param $needle
     * @return bool
     *
     * 也可以：
     * strstr($src, $needle)
     * 判断子串是否存在，返回匹配到的子串之后的串（包含子串）
     */
    public static function contains($src, $needle){
        $index = mb_strpos($src, $needle, 0, self::ENCODING);
        if($index === false){
            return false;
        }else{
            return true;
        }
    }

    public static function startWith($src, $needle){
        $index = mb_strpos($src, $needle, 0, self::ENCODING);
        if($index === false){
            return false;
        }else if($index == 0){
            return true;
        }
        return false;
    }

    public static function endWith($src, $needle){
        $index = mb_strpos($src, $needle, 0, self::ENCODING);
        if($index === false){
            return false;
        }else if($index == (self::count($src) - self::count($needle))){
            return true;
        }
        return false;
    }

    public static function substring($src, $start, $len){
        return mb_substr($src, $start, $len, self::ENCODING);
    }

    public static function replace($src, $old, $new){
        return str_replace($old, $new, $src);
    }

    /**
     * @param array $arr
     * @param $seperator
     * @param callable|null $function
     * @return string
     *
     * function joiner($key, $v){
            return $key . "-" . $v;
        }

        echo fromArray(array(1,3,4,5,6,), ",", "joiner");
        打印：0-1,1-3,2-4,3-5,4-6
     */
    public static function fromArray(array $arr, $seperator, callable $function = null){
        $str = '';
        if(!isset($arr) || count($arr) == 0){
            return $str;
        }
        foreach ($arr as $key => $value){
            $s = $function == null ? $value : $function($key, $value);
            $str .= $seperator . $s;
        }
        return self::substring($str, 1);
    }


    ///========================================================///
    public static function encodePassword($pwd){
        $salt = "14278151615aa3fb8b63d97";  //$salt = uniqid(mt_rand())
        $password = hash("sha256", $pwd);
        $stronger_password = hash("sha256", $password . $salt);
        return $stronger_password;
    }



    ///========================================================///

    /**
     * @return string 获取User Agent，如：Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36
     */
    public static function getUserAgent(){
        if(isset($_SERVER["HTTP_USER_AGENT"])){
            return $_SERVER["HTTP_USER_AGENT"];
        }
        return "";
    }


    public static function isAjax(){
        return strtolower($_SERVER["HTTP_X_REQUESTED_WITH"]) == 'xmlhttprequest';
    }

    ///========================================================///
    /**
     * 求两个已知经纬度之间的距离,单位为米
     *
     * @param lng1 $ ,lng2 经度
     * @param lat1 $ ,lat2 纬度
     * @return float 距离，单位米
     * @author www.Alixixi.com
     */
    public static function getDistance($lng1, $lat1, $lng2, $lat2) {
        // 将角度转为狐度
        $radLat1 = deg2rad($lat1); //deg2rad()函数将角度转换为弧度
        $radLat2 = deg2rad($lat2);
        $radLng1 = deg2rad($lng1);
        $radLng2 = deg2rad($lng2);
        $a = $radLat1 - $radLat2;
        $b = $radLng1 - $radLng2;
        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137 * 1000;
        return $s;
    }


    ///========================================================///
    public static function getHeader($name, $defaultValue=""){
        $key = "HTTP_" . strtoupper($name);
        if(isset($_SERVER[$key])) return $_SERVER[$key];
        else return $defaultValue;
    }

    //header("Content-type:text/html;charset=utf-8");
    public static function setHeader($name, $value){
        header($name . ":" . $value);
    }

    /**
     * header("Content-type:text/html;charset=utf-8");
     * @param string $mime
     * @param string $charset
     */
    public static function setHeaderContentType($mime="text/html", $charset="utf-8"){
        header("Content-type:" . $mime . ";charset=" . $charset);
    }

    public static function setHeaderLocation($url){
        header("Location:" . $url);
    }

    ///========================================================///
    //$_SERVER["REQUEST_METHOD"] == "POST"
    public static function getMethod(){
        return $_SERVER["REQUEST_METHOD"];
    }

    public static function isMethodGet(){
        return $_SERVER["REQUEST_METHOD"] == "GET";
    }

    public static function isMethodPost(){
        return $_SERVER["REQUEST_METHOD"] == "POST";
    }

    ///========================================================///
    public static function hasParam($name){
        if(isset($_REQUEST[$name])){
            return true;
        }
        return false;
    }

    public static function getParam($name, $defaultValue=""){
        return self::hasParam($name) ? trim($_REQUEST[$name]) : $defaultValue;
    }

    ///========================================================///
    /// session_start();
    /// session_destroy(); -- 这个不能在脚本结束时调用，要不这个用户的session就被销毁了
    public static function hasSession($name){
        if(isset($_SESSION[$name]) && isset($_SESSION[$name]['expire'])){
            if($_SESSION[$name]['expire']>time()){
                return true;
            }else{
                self::removeSession($name);
                return false;
            }
        }
        return false;
    }

    public static function getSession($name, $defaultValue=""){
        return self::hasSession($name) ? $_SESSION[$name]['data'] : $defaultValue;
    }

    public static function setSession($name, $data, $expire=600){
        $session_data = array();
        $session_data['data'] = $data;
        $session_data['expire'] = time()+$expire;
        $_SESSION[$name] = $session_data;
    }

    public static function setSessionAliveTimeSeconds($seconds){
        setcookie(session_name(), session_id(),time()+$seconds, "/");
        //最后一个参数为可选参数，是放置Cookie的路径
    }

    public static function removeSession($name){
        unset($_SESSION[$name]);
    }

    public static function removeAllSession(){
        $_SESSION = array();
    }

    ///========================================================///
    public static function hasCookie($name){
        if(isset($_COOKIE[$name])){
            return true;
        }
        return false;
    }

    public static function getCookie($name, $defaultValue=""){
        return self::hasCookie($name) ? $_COOKIE[$name] : $defaultValue;
    }

    public static function setCookie($name, $value, $aliveTimeSeconds=0){
        setcookie($name, $value, $aliveTimeSeconds != 0 ? time() + $aliveTimeSeconds : 0);
    }

    public static function removeCookie($name){
        setcookie($name, "", time()-3600);
    }


    ///========================================================///
    public static function httpGet($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //将输出作为变量返回
        curl_setopt($ch, CURLOPT_FAILONERROR, true); //如果错误发生则失败
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); //允许重定向
        curl_setopt($ch, CURLOPT_TIMEOUT, 10); //超时时间

        $data = curl_exec($ch);
        if(!$data){
            $res = array(
                "code"=>curl_errno($ch),
                "content"=>curl_getinfo($ch),
            );
            return $res;
        }

        curl_close($ch);
        return array(
            "code"=>200,
            "content"=>$data,
        );

    }

    /**
     * @param $url
     * @param null $postParams
     * @param null $headers
     * @return array
     */
    public static function httpPost($url, $postParams=null, $headers=[]){
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_HEADER, $headers);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLINFO_HEADER_OUT, true); //TRUE 时追踪句柄的请求字符串，从 PHP 5.1.3 开始可用。这个很关键，就是允许你查看请求header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //将输出作为变量返回
        curl_setopt($ch, CURLOPT_FAILONERROR, true); //如果错误发生则失败
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); //允许重定向
        curl_setopt($ch, CURLOPT_TIMEOUT, 10); //超时时间

        if(!empty($postParams)){
            $params = "";
            foreach ($postParams as $k=>$v){
                $params .= "&$k=$v";
            }
            $params = substr($params, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        }

        $data = curl_exec($ch);
        if(!$data){
            $res = array(
                "code"=>curl_errno($ch),
                "content"=>curl_getinfo($ch),
            );
            return $res;
        }

        // 获得响应结果里的：头大小
        $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        // 根据头大小去获取头信息内容
        $header = substr($data, 0, $headerSize);
        $body = str_replace($header, "", $data);
        curl_close($ch);


        $data = str_replace("\r\n", "<br/>", $data);
        return $data;

//        return array(
//            "code"=>200,
//            "content"=>$data,
//        );

    }



    ///========================================================///
    public static function str_rand($len, $chars='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'){
        if(!is_int($len) || $len < 0){
            return "";
        }
        $chars_len = self::count($chars) - 1;
        $string = '';
        for($i = $len; $i > 0; $i--){
            $string .= $chars[mt_rand(0, $chars_len)];
        }
        return $string;
    }

    public static function getRandomString($type=2, $length=4){
        if($type == 1){
            $chars = join("", range(0, 9));
        }else if($type == 2){
            $chars = join("", array_merge(range("a", "z"), range("A", "Z")));
        }else if($type == 3){
            $chars = join("", array_merge(range("a", "z"), range("A", "Z"), range(0, 9)));
        }

        if($length > strlen($chars)){
            return null;
        }

        $chars = str_shuffle($chars);
        return substr($chars, 0, $length);
    }


    ///========================================================///
    public static function sendEmail($content){
        $resp = Lang2::httpPost("http://114.215.81.196/NotCool/index.php?r=api/sendemail", [
            'to' => "279800561@qq.com",
            'content' => $content,
            'subject' => '举个牌服务器',
            'app_key' => 'z819S0q0',
        ], array(
            "notcool_device: 111",
            "notcool_user: 111"
        ));
        echo $resp; //json_encode($resp);
    }


    ///========================================================///
    public static function handleUploadFile($fileinfo, $maxsize=2097152, $allowSuffix=array('jpeg','jpg','png','gif','wbmp', 'bmp'), $isImage=true){


        if ($fileinfo['error'] > 0) {
            switch ($fileinfo['error']) {
                case 1:
                    $mes = "上传文件超过了PHP配置文件中upload_max_filesize选项的值";
                    break;
                case 2:
                    $mes = "超过了表单MAX_FILE_SIZE的限制大小";
                    break;
                case 3:
                    $mes = "文件部分被上传";
                    break;
                case 4:
                    $mes = "没有选择上传文件";
                    break;
                case 6:
                    $mes = "没有找到临时目录";
                    break;
                case 7:
                case 8:
                    $mes = "系统错误";
                    break;

            }
            return array("code"=>$fileinfo['error'], "message"=>$mes);

        }

        //判断上传文件类型是不是在规定类型中
        //3863ec1632c3ee2ac3f503所发生的.jpg
        $ext=strtolower(substr(strrchr($fileinfo['name'], '.'), 1));//截取上传文件扩展名
        if(!in_array($ext,$allowSuffix))     // 判断上传文件的扩展名是不是在定义类型中
        {
            return array("code"=>21, "message"=>"不支持的文件类型" . $ext);
        }

        //判断上传文件大小
        if($fileinfo['size']>$maxsize)
        {
            return array("code"=>22, "message"=>"上传文件过大，最大支持" . $maxsize . " byte");
        }

        //判断文件是否是通过HTTP POST方式上传上来的
        if(!is_uploaded_file($fileinfo['tmp_name']))
        {
            return array("code"=>23, "message"=>"文件不是通过HTTP POST方式上传上来的");
        }

        //检测是否为真实的图片类型，而不是认为改动的
        if($isImage)
        {
            if(!getimagesize($fileinfo['tmp_name']))
            {
                return array("code"=>24, "message"=>"不是真实的图片类型");
            }
        }


        //判断服务器上存储的文件夹在不在
        $path='uploads';  //服务器上存储文件的文件名
        if(!file_exists($path))
        {
            mkdir($path,0777,true);//不存在就创建一个目录
            chmod($path,0777);//加一个权限

        }
        $uniname=md5(uniqid(microtime(true),true)).'.'.$ext;   //通过MD5加密等措施给文件名取名，产生唯一文件名

        $destination=$path.'/'.$uniname;
        if(!move_uploaded_file($fileinfo['tmp_name'],$destination)) //上传文件
        {
            return array("code"=>25, "message"=>"文件上传失败");
        }

        return array(
            'code'=>0,
            'path'=>$destination,
            'url'=>$destination,
            'size'=>$fileinfo['size'],
            'mime'=>$fileinfo['type']
        );


    }
}